<script lang="ts" setup>
import type { FieldValues, PlusColumn } from 'plus-pro-components'

import { memberSelect, memberUpdateTag } from '@fl/api/anjutong'
import { ElCard, ElMessage, ElTable } from 'element-plus'
import { nextTick, ref } from 'vue'

import memberPage from '.././member-public/member-table-page.vue'

const props = withDefaults(defineProps<{
    memberTag?: any
    sendMemberTagId?: any
    sendMemberTagList?: any
}>(), {
    memberTag: {},
    sendMemberTagId: '',
    sendMemberTagList: [],
})
const emits = defineEmits(['pageChange', 'sendConditions', 'sendPagefun', 'fmethod'])

const newMemberTagList = ref<any>([])

const switchStatus = computed(() => (data) => {
    console.log(data, 'datadatadata')
    if (data === 1)
        return true

    else
        return false
})
const { memberTag, sendMemberTagId, sendMemberTagList } = toRefs(props)
newMemberTagList.value = sendMemberTagList.value
console.log('🚀 ~ newMemberTagList:', newMemberTagList)

const formData = ref<FieldValues>({
    nameTap: '',
    typeTag: 1,
})
// const TagCatList = ref<any>([])
const columns = reactive<PlusColumn[]>(
    [
        {
            label: '标签类型',
            options: [{
                label: '手动标签',
                value: 1,
            }, {
                label: '自动标签',
                value: 0,
            }],
            prop: 'typeTag',
            valueType: 'select',
            width: 300,
        },
        {
            label: '标签名称',
            prop: 'nameTap',
            valueType: 'copy',
            width: 300,
        },
    ],
)

type User = {
    info: string
    lastUpdateTime: string
    mainCat: string
    name: string
    status: boolean
    subCat: string

}

const memberIdListTemp = ref<any>([])
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
watch(sendMemberTagList, (nval) => {
    newMemberTagList.value = nval
    multipleSelection.value = nval
})
function handleSelectionChange(val: User[]) {
    console.log('🚀 ~ handleSelectionChange ~ val:', val)
    multipleSelection.value = val
    newMemberTagList.value = val
    console.log(multipleSelection.value, 'multipleSelection')
}
const textarea = ref('')
const tableCheckoutList = ref([])
const dialogFormVisible = ref(false)
function redactProfile() {
    dialogFormVisible.value = true
    nextTick(() => {
        toggleSelection()
    })
}
function _addMemberTag() {
    tableCheckoutList.value = multipleTableRef.value!.getSelectionRows()
    console.log(tableCheckoutList.value, 'tableCheckoutList.value')

    let tempTableCheck = {}
    tableCheckoutList.value.forEach((item: any) => {
        tempTableCheck = {
            id: item.id,
            name: item.name,
        }
        console.log(newMemberTagList.value, '为何push报错')
        newMemberTagList.value.push(tempTableCheck)
        memberIdListTemp.value.push(item.id)
    })
    for (let i = 0; i < newMemberTagList.value.length; i++) {
        for (let j = i + 1; j < newMemberTagList.value.length; j++) {
            if (newMemberTagList.value[j].id === newMemberTagList.value[i].id) {
                newMemberTagList.value.splice(j, 1)
                j--
            }
        }
    }
    console.log(newMemberTagList.value, 'sendMemberTagListss.value')
    if (tableCheckoutList.value.length !== 0) {
        ElMessage({
            message: '添加成功',
            type: 'success',
        })
    }

    multipleTableRef.value!.clearSelection()
}
function handleInputConfirm() {
    console.log(textarea.value, 'textareatextarea')
}
function resetConditions() {
    emits('sendConditions', {})
    formData.value.nameTap = ''
    formData.value.typeTag = 1
}
function handlePageTag(page: any) {
    emits('pageChange', page)
    emits('sendPagefun', page)
    console.log(page, '触发父组件的事件')
}
function editAddTag() {
    dialogFormVisible.value = false
    memberIdListTemp.value = []
    multipleSelection.value.forEach((item: any) => {
        memberIdListTemp.value.push(item.id)
    })
    const params = {
        memberId: sendMemberTagId.value,
        memberIdList: memberIdListTemp.value,
    }
    memberUpdateTag(params).then((res: any) => {
        console.log(res, '是否添加成功')
        closeDialog()
        emits('sendConditions', {})
    })
}
function toggleSelection() {
    console.log(`output->multipleTableRefsendMemberTagList`, newMemberTagList.value, memberTag.value.records)
    newMemberTagList.value.forEach((row: any) => {
        multipleTableRef.value!.toggleRowSelection(memberTag.value.records.find((item: any) => {
            return row.id === item.id
        }), true)
    })
}

function closeTag(tag: any) {
    console.log(`output->tag`, tag)
    newMemberTagList.value.splice(newMemberTagList.value.indexOf(tag), 1)
    newMemberTagList.value.forEach((item: any) => {
        memberIdListTemp.value.push(item.id)
    })
    nextTick(() => {
        multipleTableRef.value!.toggleRowSelection(memberTag.value.records.find((item: any) => {
            return tag.id === item.id
        }), false)
    })
}
function closeDialog() {
    memberSelect(sendMemberTagId.value).then((res: any) => {
        newMemberTagList.value = res
        console.log(newMemberTagList.value, 'closeDialogsendMemberTagList')
    })
    formData.value.nameTap = ''
    formData.value.typeTag = 1
}
function closeDialogTag() {
    dialogFormVisible.value = false
    emits('fmethod')
    closeDialog()
}
function queryTag() {
    console.log(formData, 'formDataformDataformData')
    emits('sendConditions', formData.value)
    nextTick(() => {
        toggleSelection()
    })
}
</script>

<template>
    <ElCard>
        <div font-700>
            会员标签<span ml-20
                      style="cursor: pointer;"
                      color="blue"
                      @click="redactProfile"
            >编辑标签</span>
        </div>

        <div class="mt-20 flex flex-wrap gap-2">
            <div v-for="(item, index) in newMemberTagList"
                 :key="index"
            >
                <el-button type="primary"
                           size="small"
                >
                    {{ item.name }}
                </el-button>
            </div>
        </div>
    </ElCard>

    <el-dialog v-model="dialogFormVisible"
               title=""
               width="1200"
               @close="closeDialog"
    >
        <div style="max-width:1100px;max-height:90px;overflow-y:auto"
             absolute
             left-36
             top-90
             z-1
             flex
             flex-wrap
        >
            <div v-for="tag in newMemberTagList"
                 :key="tag.name"

                 mb-6
                 mr-10
            >
                <el-button ml-10
                           type="primary"
                           size="small"
                >
                    {{ tag.name }}<el-icon ml-6
                                           @click="closeTag(tag)"
                    >
                        <CircleCloseFilled />
                    </el-icon>
                </el-button>
            </div>
        </div>

        <el-input v-model="textarea"
                  w-2400
                  :rows="4"
                  type="textarea"
                  placeholder=""
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
        />

        <div mt-40
             flex
             justify-between
        >
            <PlusForm v-model="formData"
                      :columns="columns"
                      :row-props="{ gutter: 20 }"
                      :col-props="{
                          span: 12,
                      }"

                      :has-footer="false"
                      style="width:60%"
            />

            <div style="width:20%"
                 flex
                 justify-end
            >
                <div>
                    <el-button type="primary"
                               class="mr-10"
                               @click="queryTag"
                    >
                        查询
                    </el-button>
                </div>

                <div>
                    <el-button @click="resetConditions">
                        重置
                    </el-button>
                </div>

                <!-- <div>
                    <el-button @click="addMemberTag">
                        添加
                    </el-button>
                </div> -->
            </div>
        </div>

        <div>
            <ElTable ref="multipleTableRef"
                     :data="memberTag.records"
                     style="width: 100%"
                     height="400"
                     :border="true"
                     @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection"
                                 width="55"
                />

                <el-table-column label="标签名称">
                    <template #default="scope">
                        {{ scope.row.name }}
                    </template>
                </el-table-column>

                <el-table-column property="mainCat"
                                 label="一级分类"
                                 show-overflow-tooltip
                />

                <el-table-column property="subCat"
                                 label="二级分类"
                                 show-overflow-tooltip
                />

                <el-table-column property="info"
                                 label="说明"
                                 show-overflow-tooltip
                />

                <el-table-column property="status"
                                 label="状态"
                                 show-overflow-tooltip
                >
                    <template #default="scope">
                        <el-switch :model-value="switchStatus(scope.row.status)" />
                    </template>
                </el-table-column>

                <el-table-column property="lastUpdateTime"
                                 label="最后修改时间"
                />
            </ElTable>

            <member-page :total="memberTag.total"
                         @handle-page="handlePageTag"
            />
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeDialogTag">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="editAddTag"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
